package com.yix.admin.modules.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.yix.admin.modules.system.entity.SysDept;
import com.yix.admin.modules.system.entity.dto.SysDeptDto;
import com.yix.admin.modules.system.entity.query.SysDeptQuery;
import com.yix.admin.modules.system.service.SysDeptService;
import com.yix.common.exception.BadRequestException;
import com.yix.common.utils.PageUtil;
import com.yix.logging.annotation.LogAop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author wdx
 * @version 1.0
 * @Description TODO
 * @date 2021/2/5 15:24
 */
@RestController
@Api(tags = "系统：部门管理")
@RequestMapping("/api/dept")
public class SysDeptController {

    @Autowired
    private SysDeptService sysDeptService;

    private static final String ENTITY_NAME = "dept";

    @ApiOperation("导出部门数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('dept:list')")
    public void download(HttpServletResponse response, SysDeptQuery criteria) throws Exception {
        sysDeptService.download(sysDeptService.queryAll(criteria, false), response);
    }

    @ApiOperation("查询部门")
    @GetMapping
    @PreAuthorize("@el.check('user:list','dept:list')")
    public ResponseEntity<Object> query(SysDeptQuery criteria) throws Exception {
        List<SysDeptDto> deptDtos = sysDeptService.queryAll(criteria, true);
        return new ResponseEntity<>(PageUtil.toPage(deptDtos, deptDtos.size()), HttpStatus.OK);
    }

    @ApiOperation("查询部门:根据ID获取同级与上级数据")
    @PostMapping("/superior")
    @PreAuthorize("@el.check('user:list','dept:list')")
    public ResponseEntity<Object> getSuperior(@RequestBody List<String> ids) {
        Set<SysDeptDto> deptDtos  = new LinkedHashSet<>();
        for (String id : ids) {
            SysDeptDto deptDto = sysDeptService.findById(id);
            List<SysDeptDto> depts = sysDeptService.getSuperior(deptDto, new ArrayList<>());
            deptDtos.addAll(depts);
        }
        return new ResponseEntity<>(sysDeptService.buildTree(new ArrayList<>(deptDtos)),HttpStatus.OK);
    }

    @LogAop("新增部门")
    @ApiOperation("新增部门")
    @PostMapping
    @PreAuthorize("@el.check('dept:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody SysDept resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        sysDeptService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @LogAop("修改部门")
    @ApiOperation("修改部门")
    @PutMapping
    @PreAuthorize("@el.check('dept:edit')")
    public ResponseEntity<Object> update(@Validated(SysDept.Update.class) @RequestBody SysDept resources){
        sysDeptService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @LogAop("删除部门")
    @ApiOperation("删除部门")
    @DeleteMapping
    @PreAuthorize("@el.check('dept:del')")
    public ResponseEntity<Object> delete(@RequestBody Set<String> ids){
        Set<SysDeptDto> deptDtos = new HashSet<>();
        for (String id : ids) {
            List<SysDept> deptList = sysDeptService.findByPid(id);
            deptDtos.add(sysDeptService.findById(id));
            if(CollectionUtil.isNotEmpty(deptList)){
                deptDtos = sysDeptService.getDeleteDepts(deptList, deptDtos);
            }
        }
        // 验证是否被角色或用户关联
        sysDeptService.verification(deptDtos);
        sysDeptService.delete(deptDtos);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
